package phase01.module3.code.question5;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Table牌桌类，一副扑克，3个玩家
 * 牌桌继承斗地主主类，表示此桌用来打斗地主
 */
public class Table extends PeasantVsLandlord implements CardAction {
    private Player p1;
    private Player p2;
    private Player p3;
    private Player landLord; // 指向三个玩家中的一个
    private List<Card> cards;
    private List<Card> playedCards;

    private Table() {
        cards = new ArrayList<>();
        Card card;
        int rank;
        int serial;
        for (int i = 1; i <= 13; i++) {
            serial = i;
            if(serial == 1) {
                rank = 14;
            }else if(serial == 2) {
                rank = 15;
            } else {
                rank = serial;
            }
            card = new Card(serial, CardSuit.CLUB, rank);
            cards.add(card);
            card = new Card(serial, CardSuit.DIAMOND, rank);
            cards.add(card);
            card = new Card(serial, CardSuit.HEART, rank);
            cards.add(card);
            card = new Card(serial, CardSuit.SPADE, rank);
            cards.add(card);
        }
        card = new Card(14, CardSuit.NONE, 16);
        cards.add(card);
        card = new Card(15, CardSuit.NONE, 17);
        cards.add(card);
    }

    public Table(Player p1, Player p2, Player p3) {
        this();
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
    }

    public void showAll() {
        Iterator<Card> iterator = cards.iterator();
        while(iterator.hasNext()) {
            Card card = iterator.next();
            if(iterator.hasNext()) {
                System.out.print(card + ", ");
            } else {
                System.out.print(card);
            }
        }
        System.out.println();
    }

    public void shuffle() {
        Collections.shuffle(cards);
    }

    @Override
    Player win() {
        return p1;
    }

    @Override
    public Card drawCard() {
        int lastIndex = cards.size() - 1;
        Card top = cards.get(lastIndex);
        cards.remove(lastIndex);
        return top;
    }

    @Override
    public void playCard(Player player, List<Card> cards) {
        playedCards.addAll(cards);
        if (player.getNumOfLeftCards() == 0) {
            System.out.println(player.getName() + "Won!");
        }
    }
}
